
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>

int fd;

/* signal_callback */
void sr501_signal_callback(int num)
{
    int val;
    int ret;
    
    ret = read(fd, &val, 4);
    if(ret > 0)
    {
        if(val) {
            printf("检测到人体, get status : 0x%x\n", val);
        } 
        else {
            printf("人已离开\n");
        }
    }
    else {
        printf("[ERR] fail to read data !!!\n");
    }
}

/*
 * ./sr501_xxx_test /dev/sr501
 *
 */
int main(int argc, char **argv)
{
    int flags;
    int val;
    int ret;
    
    /* 1. 判断参数 */
    if (argc != 2) 
    {
        printf("Usage: %s <dev>\n", argv[0]);
        return -1;
    }

    /* 2. 打开文件 */
    fd = open(argv[1], O_RDWR);
    if (fd == -1)
    {
        printf("can not open file %s\n", argv[1]);
        return -1;
    }

    /* 启动信号机制 */
    signal(SIGIO, sr501_signal_callback);
    fcntl(fd, F_SETOWN, getpid());
    flags = fcntl(fd, F_GETFL);
    fcntl(fd, F_SETFL, flags | FASYNC);

    while (1)
    {
        printf("Wellcom to SR501\n", val);
        sleep(2);
    }
    
    close(fd);
    
    return 0;
}


